package com.easyexcel.write;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;

import com.easyexcel.annotation.Excel;
import com.easyexcel.util.ExcelUtil;
import com.easyexcel.write.style.CommonCellStyle;
import com.easyexcel.write.style.MyCellStyle;
import com.easyexcel.write.util.WriteListExcelHelp;

public class WriteListExcel<T> implements WriteExcel<T>{
	private MyCellStyle cellStyle;
	private boolean isNeedSequence;
	private Workbook workbook;
	private Sheet sheet;
	private int beginNum = 1;
	private int sheetSize;
	private String outFilePath;
	private String sheetName;
	@Override
	public boolean write(Map<String,Object> param,List<T> list) throws IOException, IllegalArgumentException, IllegalAccessException {
		WriteListExcelHelp<T> help = new WriteListExcelHelp<T>();
		initParam(param,list.get(0).getClass());
		if(list.size()>sheetSize){
			double sn = (double)list.size()/sheetSize;
			sn = Math.ceil(sn);
			int initBeginNum = beginNum;
			for(int i=1;i<=sn;i++){
				beginNum = initBeginNum;
				sheet = workbook.createSheet(sheetName+"-"+i);
				help.generateHeader(sheet, beginNum, cellStyle, list.get(0).getClass());
				List<T> subList = null;
				if(sheetSize*i>list.size())
					subList = list.subList(sheetSize*(i-1), list.size());
				else
					subList = list.subList(sheetSize*(i-1), sheetSize*i);
				for(T t : subList){
					help.generateBody(sheet, beginNum++, cellStyle, t);
				}
			}
		}else{
			sheet = workbook.createSheet(sheetName);
			help.generateHeader(sheet,beginNum,cellStyle,list.get(0).getClass());
			for(T t : list){
				help.generateBody(sheet, beginNum++, cellStyle, t);
			}
		}
		ExcelUtil.workbookToFile(workbook,outFilePath);
		return true;
	}

	private void initParam(Map<String, Object> param, Class clazz) {
		if(param.get("workbook")==null)
			workbook = new HSSFWorkbook();
		else
			workbook = (Workbook) param.get("workbook");
		if(param.get("myCellStyle")==null)
			cellStyle = new CommonCellStyle(workbook);
		else
			cellStyle = (MyCellStyle)param.get("myCellStyle");
		Excel excel = (Excel) clazz.getAnnotation(Excel.class);
		com.easyexcel.annotation.Sheet s = (com.easyexcel.annotation.Sheet) clazz.getAnnotation(com.easyexcel.annotation.Sheet.class);
		if(excel!=null){
			sheetName = s.sheetName(); 
			sheetSize = s.sheetSize();
			isNeedSequence = excel.isNeedSequence();
			outFilePath = excel.outFilePath();
			beginNum = excel.beginRow();
		}
		if(param.get("outFilePath")!=null)
			outFilePath = param.get("outFilePath").toString();
		if( param.get("beginRow")!=null)
			beginNum = Integer.parseInt(param.get("beginRow").toString());
	}
	
}
